package com.gpframework.common.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;


@Slf4j
public class JsonUtils {
    private static ObjectMapper json;
    static {
        json = new ObjectMapper();
        json.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        json.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 序列化为JSON字符串
     */
    public static String ObjectToString(Object object) {
        try {
            return (json.writeValueAsString(object));
        } catch (Exception e) {
            log.error("序列化为JSON字符串出错",e);
        }
        return null;
    }

    public static <T> T getObject(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString))
            return null;
        try {
            return json.readValue(jsonString, clazz);
        } catch (Exception e) {
            log.error("将JSON字符串转化为Map出错",e);
            return null;
        }
    }

}
